package com.jd.user.controller;

import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.PageList;
import com.jd.user.domain.User;
import com.jd.user.query.UserQuery;
import com.jd.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 后端接口类；
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;

    /**
     * 接口：添加或修改
     *
     * @param user 传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user) {
        if (user.getId() != null) {
            userService.update(user);
        } else {
            userService.add(user);
        }
        return new AjaxResult();

    }

    /**
     * 接口：删除
     *
     * @param id
     * @return AjaxResult 响应给前端
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        userService.del(id);
        return new AjaxResult();
    }

    /**
     * 接口：批量删除
     *
     * @param ids
     * @return AjaxResult 响应给前端
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids) {
        userService.patchDel(ids);
        return new AjaxResult();
    }

    /**
     * 接口：查询单个对象
     *
     * @param id
     */
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") Long id) {
        return userService.findOne(id);
    }


    /**
     * 接口：查询所有
     *
     * @return
     */
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }


    /**
     * 接口：分页查询或高级查询
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query) {
        return userService.queryPage(query);
    }

    /**
     * 手机注册
     * @param map
     * @return
     */
    @PostMapping("/register/phone")
    public AjaxResult phoneRegister(@RequestBody Map<String, String> map) {
        return userService.phoneRegister(map);
    }

    /**
     * 邮箱注册
     * @param map
     * @return
     */
    @PostMapping("/register/email")
    public AjaxResult emailRegister(@RequestBody Map<String, String> map) {
        return userService.emailRegister(map);
    }

    /**
     * 邮箱激活
     * @param id
     * @param response
     */
    @GetMapping("/active/{id}")
    public void emailActive(@PathVariable("id") Long id, HttpServletResponse response) {
        userService.emailActive(id);
        try {
            response.sendRedirect("http://127.0.0.1/login.html");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
